import torch
import csv
from torch import nn
from torch.optim import Adam
import requests
import sklearn
import json


class StockRecurrentAnalysis(nn.Module):

    def __init__(self, batch_size, input_size, hidden_size, num_layers, output_size, predict_size, lr=1e-3):
        super(StockRecurrentAnalysis, self).__init__()
        self.lr = lr
        self.optimizer = None
        self.batch_size = batch_size
        self.analysis_rnn = nn.LSTM(
            input_size=input_size,
            hidden_size=hidden_size,
            num_layers=num_layers,
            batch_first=True
        )
        self.fc1 = nn.Linear(hidden_size, output_size)
        self.fc2 = nn.Linear(output_size, predict_size)

    def forward(self, stock_data):
        rnn_out, (hidden_s, hidden_c) = self.analysis_rnn(stock_data)
        return rnn_out, hidden_s, hidden_c

    def train(self, x, y):
        # x shape is [batch_size,time_step,features]
        # y shape is [batch_size,time_step,features]
        if self.optimizer is None:
            self.optimizer = Adam(self.parameters(), self.lr)
        optimizer = self.optimizer
        # 计算loss

        optimizer.zero_grad()
        # 反向传播

        # 更新参数


def get_stock_raw(stock_code):
    # url = "http://stock.liangyee.com/bus-api/stock/freeStockMarketData/get5MinK"
    url = "http://stock.liangyee.com/bus-api/stock/freeStockMarketData/getDailyKBar"

    security = get_security_by()
    s_type = 0 if stock_code.startswith("6") else 1
    params = {
        "startDate": "2018-01-01",
        "endDate": "2018-04-22",
        "userKey": security,
        "symbol": stock_code,
        "type": s_type
    }
    '''
    params = {
        "userKey": security,
        "symbol": stock_code,
        "type": s_type
    }
    '''
    resp = requests.get(url, params)
    if resp.status_code == 200:
        stock_info = resp.json()
        return stock_info
    else:
        print("无法调用api")
        raise BaseException("错误，无法调用，未知")


def get_stock_data():
    stock_info = get_stock_raw("600220")
    mm = sklearn.preprocessing.MinMaxScaler()
    mm.fit()


def get_data_set(file):
    csv_dat = csv.reader(open(file, "r", encoding='UTF8'))
    jackson = []
    for line in csv_dat:
        jackson.append(line)
    return jackson


def get_security_by():
    user_se = [
        "369732e07fe54c65b3d4265a3e938c6e"
    ]
    return user_se[0]
